package com.xjh.serverinspect.security.handler;

import com.alibaba.fastjson2.JSON;
import com.xjh.serverinspect.security.ResponseBodyHandler;
import com.xjh.serverinspect.util.ResponseCodeEnum;
import com.xjh.serverinspect.util.ResponseDTO;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 无权访问处理
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-12
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(JSON.toJSONBytes(ResponseBodyHandler.encrypt(ResponseDTO.error(ResponseCodeEnum.FORBIDDEN), req)));
        outputStream.flush();
        outputStream.close();
    }
}

